import time
import serial
from PyQt5.QtCore import QThread, pyqtSignal

class SerialThread(QThread):
    data_received = pyqtSignal(str)
    send_progress = pyqtSignal(int)
    
    def __init__(self, port, baudrate):
        super().__init__()
        self.ser = serial.Serial(port, baudrate, timeout=1)
        self.running = True
        self.byte_interval = 0  # 单位为秒
        
    def run(self):
        while self.running:
            if self.ser.in_waiting:
                data = self.ser.read(self.ser.in_waiting).decode('latin1')
                self.data_received.emit(data)
    
    def send_data(self, data, chunk_size=1024, with_progress=False, add_newline=True):
        """分块发送数据（适合大文件）"""
        if isinstance(data, str):
            data = data.encode('latin1')
        
        if add_newline and not data.endswith(b'\r\n'):
            data += b'\r\n'

        total = len(data)
        sent = 0
        
        while sent < total:
            chunk = data[sent:sent + chunk_size]
            self.ser.write(chunk)  # 发送一个 chunk
            sent += len(chunk)
            
            if with_progress:
                self.send_progress.emit(int(sent / total * 100))
            
            # 可选的短暂延迟（防止 MCU 缓冲区溢出）
            if self.byte_interval > 0:
                time.sleep(self.byte_interval * 0.01)  # 降低延迟

    def stop(self):
        self.running = False
        if self.ser.is_open:
            self.ser.close()